﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JigLibX.Collision;
using PloobsEngine.Physics.XJigLib;
using PloobsEngine.Events;
using PloobsEngine.Physics;

namespace PloobsEngine.Trigger
{
    public class JigLibXTriggerAfter : ITrigger
    {
        private JigLibXObject ghost;
        private IList<CollisionSkin> _excepts = new List<CollisionSkin>();
        IEvent<ITrigger> now;
        IEvent<ITrigger> after;

        public JigLibXTriggerAfter(JigLibXObject ghost, IEvent<ITrigger> now, IEvent<ITrigger> after)
        {
            this.ghost = ghost;
            ghost.Body_.CollisionSkin.callbackFn += new CollisionCallbackFn(handleCollisionDetection);
            this.now = now;
            this.after = after;

        }

        public JigLibXObject CollisionExcepts
        {
            set
            {
                _excepts.Add(value.Body_.CollisionSkin);
            }
        }

        private bool aftersignal = false;
        private bool handleCollisionDetection(CollisionSkin owner, CollisionSkin collidee)
        {
            if (!_excepts.Contains(collidee) && collidee.Owner != null && !collidee.Owner.Immovable)
            {
                now.FireEvent(this);
                aftersignal = true;
            }
            else
            {
                if (aftersignal)
                {
                    after.FireEvent(this);
                    aftersignal = false;
                }
            }
            return false;
            

            
        }

        #region ITrigger Members

        public void Handle()
        {
            now.FireEvent(this);

        }
        
        public IPhysicObject GhostObject
        {
            get
            {
                return ghost;
            }
            set
            {
                this.ghost = value as JigLibXObject; ;
            }
        }

        #endregion


        #region ITrigger Members

        public string Name
        {
            get;
            set;
        }

        #endregion

        #region ITrigger Members

        IEvent<ITrigger> ITrigger.Event
        {
            get
            {
                return now;
            }
            set
            {
                this.now = value;
            }
        }

        #endregion
    }
}
